<template>
  <div class="avatar">
    <div @mouseover="showBg=true" @mouseleave="showBg=false">
      <div v-if="showBg" class="bg" :style="`line-height:${imgHeight}`">点击上传</div>
      <input
        ref="avatarInput"
        type="file"
        class="input-file"
        :style="`width:${imgWidth};height:${imgHeight};`"
        name="avatar"
        accept="image/gif,image/jpeg,image/jpg,image/png"
        @change="changeImage($event)"
      >
      <img
        :src="avatar?avatar:require('./img/logo.png')"
        alt=""
        :style="`width:${imgWidth};height: ${imgHeight};`"
        name="avatar"
      >
    </div>
    <div v-if="file" class="text" @click="upload">确定上传</div>
  </div>
</template>

<script>
export default {
  name: 'Upload',
  // eslint-disable-next-line vue/require-prop-types
  props: ['uploadType', 'imgUrl', 'imgWidth', 'imgHeight'],
  data() {
    return {
      avatar: '',
      file: '',
      showBg: false
    }
  },
  created(){
    this.avatar = this.imgUrl
  },
  methods: {
    changeImage(e){
      const file = e.target.files[0]
      if(file) {
        this.file = file
        console.log(this.file)
        const reader = new FileReader()
        const that = this
        reader.readAsDataURL(file)
        reader.onload= function(e){
          // 这里的this 指向reader
          that.avatar = this.result
        }
      }
    },
    upload(){
      const files = this.$refs.avatarInput.files
      let fileData = {}
      if(files instanceof Array) {
        fileData = files[0]
      } else {
        fileData = this.file
      }
      // console.log('fileData', typeof fileData, fileData)
      const data = new FormData()
      data.append('multfile', fileData)
      data.append('operaType', this.uploadType)
    }
  }
}

</script>

<style lang="scss" scoped>

</style>
